<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Menu extends BaseController {
    public function __construct() {
        parent::__construct();

        // 移动端初始化方法
        $this->wx_init();
        
        // 加载库
        $this->load->model('schoolModel');
        $this->load->model('configModel');
        $this->load->model('wxAppliModel');
    }

    /*
     * 菜单页面
     */
    public function index() {
        $this->load->model('staffModel');
        $this->htmlTitle = '菜单';
        // 获取招考查询地址
        $this->examQueryLink = '';
        $link = $this->configModel->get_config_info('exam_query_link', true);
        if(!empty($link)){
            $this->examQueryLink = $link;
        }
        // 获取所有应用
        $params['bindUserType'] = $this->bindUserType;
        $params['isDelete'] = 0;
        // 排序
        $params['orderBy'] = 'sort_level DESC';
        // 关联后台admin_menu表
        // 外链的admin_menu_id=0
        $adminMenuIdArr = array();
        $schoolInfo = array();
        // 支持管理员
        if($this->bindUserType == BIND_TYPE_STUDENT || ($this->bindUserType == BIND_TYPE_TEACHER && $this->user['user_type'] == USER_TYPE_SCHOOL)) {
            // 学生：后台学校功能权限对应
            $schoolInfo = $this->schoolModel->get_school_info($this->user['school_id']);
            $adminMenuIdArr = explode(',', $schoolInfo['school_module_set']);
        } else {
            // 教师：后台教师角色组功能权限对应
            $roleIdSet = $this->user['role_id_set'];
            $roleIdArr = explode(',', $roleIdSet);
            // 获取学校角色列表
            $roleList = $this->staffModel->get_role_list($this->user['school_id']);
            // 使用id作为键值
            $roleList = array_value_to_key($roleList, 'id');
            foreach($roleIdArr as $roleId) {
                if(isset($roleList[$roleId])) {
                    $menuSet = $roleList[$roleId]['role_menu'];
                    if($menuSet) {
                        $menuArr = explode(',', $menuSet);
                        $adminMenuIdArr = array_merge($adminMenuIdArr, $menuArr);
                    }
                }
            }

            $schoolInfo = $this->schoolModel->get_school_info($this->user['school_id']);
            $schoolAdminMenuIdArr = explode(',', $schoolInfo['school_module_set']);
            // 判断是否在学校权限里
            foreach($adminMenuIdArr as $key => $id) {
                if(!in_array($id, $schoolAdminMenuIdArr)) {
                    unset($adminMenuIdArr[$key]);
                }
            }
        }
        array_push($adminMenuIdArr, '0');
        $params['adminMenuIdArr'] = array_unique($adminMenuIdArr);
        // var_export($this->user['school_id']);exit;
        $params['excludeTitleArr'] = array();
        if(!DEBUG && $this->user['school_id'] == '23') {
            // 湖南新瀚高中去除‘对话留言’
            $params['excludeTitleArr'] = array('对话留言');
        }
        // 没开通教师考勤的学校去掉‘教师考勤’菜单
        if(empty($schoolInfo) || $schoolInfo['enable_teacher_sign'] == 0) {
            $params['excludeTitleArr'][] = '教师考勤';
        }
        // 没开通闸机的学校去掉‘闸机记录’菜单
        $gateParams['schoolId'] = $schoolInfo['id'];
        $gateParams['isDelete'] = 0;
        $gateList = $this->schoolModel->get_gate_list($gateParams);
        if(empty($gateList)) {
            $params['excludeTitleArr'][] = '闸机记录';
        }
        $applications = $this->wxAppliModel->get_wx_application_list($params);
        // var_export($applications);exit;
        // 处理自定义外链
        foreach($applications as $key => $value) {
            if($value['custom_menu_id'] != 0) {
                $customMenu = $this->schoolModel->get_custom_menu_info($value['custom_menu_id']);
                if($customMenu['is_delete'] || $customMenu['school_id'] != $this->user['school_id']) {
                    // 去掉外链
                    unset($applications[$key]);
                } else {

                    // var_export($customMenu);exit;
                    $applications[$key]['link'] = $customMenu['link'];
                    $applications[$key]['title'] = $customMenu['title'];
                    $applications[$key]['icon'] = $customMenu['icon'];
                }
            }
        }
        // 获取当前用户应用
        $params['userId'] = $this->user['id'];
        $userAppli = $this->wxAppliModel->get_wx_user_appli($params);
        $userAppliIdArr = array();
        if($userAppli['appli_ids']) {
            // 用户已添加过
            $userAppliIdArr = explode(',', $userAppli['appli_ids']);
            // 兼容之前可以8个
            if(count($userAppliIdArr) === 8) {
                array_pop($userAppliIdArr);
            }
        } else {
            // 如未添加过，默认已添加前7个应用
            foreach($applications as $key => $application) {
                if($key < 7) {
                    array_push($userAppliIdArr, $application['id']);
                }
            }
        }
        // 用户已添加应用列表
        $addList = array();
        // 未添加应用列表
        $notAddList = array();
        foreach($applications as $application) {
            // 是否已添加
            $added = false;
            if(in_array($application['id'], $userAppliIdArr)) {
                $added = true;
            }
            if($added) {
                array_push($addList, $application);
            } else {
                array_push($notAddList, $application);
            }
        }
       // 卡号过期处理
       if($this->user['expired']) {
            $list = $this->wxAppliModel->get_wx_application_list(array(
                'bindUserType' => BIND_TYPE_STUDENT,
                'includeTitleArr' => array('班级通知', '校园公告')
            ));
            $addList = $list;
            $notAddList = array();
        }
        $this->addList = $addList;
        $this->notAddList = $notAddList;

                // echo '<pre>';var_export($notAddList);exit;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . "menu");
    }

    // 保存应用操作
    public function save_user_application() {
        $appliIdArr = $this->post('appliIdArr');
        if(empty($appliIdArr)) {
            throw new Exception("请添加'我的应用'");
        }
        $appliIds = implode(',', $appliIdArr);
        $userId = $this->user['id'];
        $bindUserType = $this->bindUserType;
        // 获取当前用户应用
        $params['bindUserType'] = $bindUserType;
        $params['isDelete'] = 0;
        $params['userId'] = $userId;
        $userAppli = $this->wxAppliModel->get_wx_user_appli($params);
        $data = array(
            'user_id' => $userId,
            'appli_ids' => $appliIds,
            'bind_user_type' => $bindUserType,
            'is_delete' => 0,
            'createtime' => date('Y-m-d H:i:s'),
            'updatetime' => date('Y-m-d H:i:s')
        );
        if($userAppli) {
            // 更新
            $this->db->where('id', $userAppli['id']);
            $this->db->update(WxAppliModel::$wxUserAppliTable, $data);
        } else {
            // 插入
            $this->db->insert(WxAppliModel::$wxUserAppliTable, $data);
        }
        exit(json('', true));
    }
}